﻿using MetaView.Main.Models;
using MetaView.Main.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Windows;
using Wpf.Ui;
using Wpf.Ui.DependencyInjection;

namespace MetaView.Client
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App
    {
        private static readonly IHost _host = Host.CreateDefaultBuilder()
        .ConfigureAppConfiguration(c =>
        {
            var basePath = Path.GetDirectoryName(AppContext.BaseDirectory) ?? throw new DirectoryNotFoundException("找不到应用程序根目录");
            _ = c.SetBasePath(basePath);
        })
        .ConfigureServices(
            (context, services) =>
            {
                _ = services.AddNavigationViewPageProvider();

                // 应用程序主机
                _ = services.AddHostedService<ApplicationHostService>();

                // 主题
                _ = services.AddSingleton<IThemeService, ThemeService>();

                // 任务栏
                _ = services.AddSingleton<ITaskBarService, TaskBarService>();

                // 导航 与INavigationWindow相同 没有窗体
                _ = services.AddSingleton<INavigationService, NavigationService>();

                // 主窗口
                _ = services.AddSingleton<INavigationWindow, Views.MainWindow>();
                _ = services.AddSingleton<Main.ViewModels.MainWindowViewModel>();

                // 视图和视图模型
                _ = services.AddSingleton<Main.Views.Pages.DashboardPage>();
                _ = services.AddSingleton<Main.ViewModels.DashboardViewModel>();
                _ = services.AddSingleton<Main.Views.Pages.DataPage>();
                _ = services.AddSingleton<Main.ViewModels.DataViewModel>();
                _ = services.AddSingleton<Main.Views.Pages.SettingsPage>();
                _ = services.AddSingleton<Main.ViewModels.SettingsViewModel>();

                // 配置
                _ = services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
            }
        )
        .Build();

        /// <summary>
        /// 获取服务
        /// </summary>
        public static IServiceProvider Services
        {
            get { return _host.Services; }
        }

        /// <summary>
        /// 应用程序启动事件
        /// </summary>
        private async void OnStartup(object sender, StartupEventArgs e)
        {
            await _host.StartAsync();
        }

        /// <summary>
        /// 应用程序关闭事件
        /// </summary>
        private async void OnExit(object sender, ExitEventArgs e)
        {
            await _host.StopAsync();

            _host.Dispose();
        }
    }
}
